 //
//  ScheduleInspectionViewController.m
//  FMS
//
//  Created by Steven on 10/12/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "ScheduleInspectionViewController.h"
#import "ScheduleFilterViewController.h"
#import "ListScheduleViewController.h"
#import "DetailedItemViewController.h"
#import "MaintenanceDetailedViewController.h"
#import "SelectContractorViewController.h"

#import <QuartzCore/QuartzCore.h>

@interface ScheduleInspectionViewController ()

@end
enum IndexSelectDate {
    StartDateIndex = 1,
    EndDateIndex
};
@implementation ScheduleInspectionViewController
@synthesize isEditting;
@synthesize dictSchedule = _dictSchedule;
@synthesize delegate;
@synthesize isCheckEditting;
//vinh
@synthesize inputInspectionDict;
@synthesize inputMaintenanceDict;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil schedule:(NSMutableDictionary *)schedule
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        self.dictSchedule = schedule;
    }
    return self;
}

#pragma mark utils method

- (void)selectServiceType:(UIButton *)sender{
    if ([delegate isKindOfClass:[ScheduleFilterViewController class]]) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else{
        ScheduleFilterViewController *controller = [[ScheduleFilterViewController alloc] initWithNibName:@"ScheduleFilterViewController" bundle:[NSBundle mainBundle]];
        controller.delegate = self;
        controller.dictFilter = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[_dictSchedule objectForKey:@"scheduleCategory"],@"scheduleCategory",[_dictSchedule objectForKey:@"categoryId"],@"categoryId",[_dictSchedule objectForKey:@"service"],@"service",[_dictSchedule objectForKey:@"camp"],@"camp",[_dictSchedule objectForKey:@"unit"],@"unit",[_dictSchedule objectForKey:@"building"],@"building",[_dictSchedule objectForKey:@"floor"],@"floor",[_dictSchedule objectForKey:@"room"],@"room",[_dictSchedule objectForKey:@"itemType"],@"itemType", nil];
        [self.navigationController pushViewController:controller animated:YES];
    }
}
- (void)selectMaintenanceType:(UIButton *)sender{
    [self didmissPopoverController];
    
    FilterViewController *controller;
    controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filter_maintenance];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:sender.frame inView:[sender superview] permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (void)selectTypeRequirement:(UIButton *)sender{
    [self didmissPopoverController];
    
    FilterViewController *controller;
    controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filter_inspection];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:sender.frame inView:[sender superview] permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (void)selectStartDate:(UIButton *)sender{
    indexSelectDate = StartDateIndex;
    
    [self didmissPopoverController];
    DatePickerViewController *controller = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:[NSBundle mainBundle] dateSelect:[NSDate date]];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:sender.frame inView:sender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    controller.lblTitleView.text = [dictLanguage objectForKey:@"schedule.title-starting-date"];
}

- (void)selectEndDate:(UIButton *)sender{
    indexSelectDate = EndDateIndex;
    
    [self didmissPopoverController];
    DatePickerViewController *controller = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:[NSBundle mainBundle] dateSelect:[NSDate date]];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:sender.frame inView:sender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    controller.lblTitleView.text = [dictLanguage objectForKey:@"schedule.title-ending-date"];
}

- (void)selectPersonInCharge:(UIButton *)sender{
    [self didmissPopoverController];
    ListPersonInChargeViewController *controller = [[ListPersonInChargeViewController alloc] initWithStyle:UITableViewStylePlain];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:sender.frame inView:sender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
- (void)updateContentServiceItem{
    lblInServiceType.text = [NSString stringWithFormat:@"%@, %@, %@, %@, %@",[_dictSchedule objectForKey:@"room"],[_dictSchedule objectForKey:@"floor"],[_dictSchedule objectForKey:@"building"],[_dictSchedule objectForKey:@"unit"],[_dictSchedule objectForKey:@"camp"]];
        
}
- (void)reloadInfoSchedule{
    [self updateContentServiceItem];

    if (isEditting && !isCheckEditting) {
        [btnTypeRequirment converToLabel];
        [btnMaintenanceType converToLabel];
        
        [btnStartDate converToLabel];
        [btnWorkingType converToLabel];
        [btnItemType converToLabel];
        [btnLastUpdate converToLabel];
        lblBorderRemark.layer.borderWidth = 0;
        
        tvRemark.userInteractionEnabled = NO;
        
        if (self.navBar) {
            [self.navBar.rightButton setBackgroundImage:[UIImage imageNamed:@"btnEdit.png"] forState:UIControlStateNormal];
        }
    }
    else{

        [btnTypeRequirment converCombobox];
        [btnMaintenanceType converCombobox];
        [btnWorkingType returnDefaultCustom];
        [btnItemType returnDefaultCustom];
        
        [btnLastUpdate returnDefaultCustom];
        [btnTypeRequirment returnDefaultCustom];
        [btnMaintenanceType returnDefaultCustom];
        [btnStartDate returnDefaultCustom];
        
        tvRemark.userInteractionEnabled = YES;
        lblBorderRemark.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        lblBorderRemark.layer.borderWidth = 1;
        
    }
    // update content schedule
    if (![delegate isKindOfClass:[DetailedInfoViewController class]]) {
        if ([[_dictSchedule objectForKey:@"categoryId"] intValue] == Maintenance){
            [btnWorkingType setTitle:[_dictSchedule objectForKey:@"maintenanceType"] forState:UIControlStateNormal];
        }
        else
            [btnWorkingType setTitle:[_dictSchedule objectForKey:@"scheduleCategory"] forState:UIControlStateNormal];
        
        if ([[_dictSchedule objectForKey:@"itemType"] intValue] == Building_Type) {
            [btnItemType setTitle:[dictLanguage objectForKey:@"schedule.title-building"] forState:UIControlStateNormal];
        }
        else
            [btnItemType setTitle:[dictLanguage objectForKey:@"schedule.title-facility"] forState:UIControlStateNormal];
    }
   
    if (isCheckEditting) {
        if (self.navBar) {
            if ([delegate isKindOfClass:[MaintenanceDetailedViewController class]]) {
                [self.navBar.rightButton setBackgroundImage:[UIImage imageNamed:@"btnSendMail.png"] forState:UIControlStateNormal];
            }
            else
                [self.navBar.rightButton setBackgroundImage:[UIImage imageNamed:@"btnSave.png"] forState:UIControlStateNormal];
        }
    }
    if (_dictSchedule) {
        if ([delegate isKindOfClass:[DetailedInfoViewController class]])
        {
            if ([[_dictSchedule objectForKey:@"categoryId"] intValue] == Maintenance)
            {
                typemaintenance = [[_dictSchedule objectForKey:@"maintenanceTypeId"] intValue];
                switch (typemaintenance) {
                    case 0:
                        [btnMaintenanceType setTitle:[dictLanguage objectForKey:@"maintenance-mgmt.add-new.select-maintenance-type"] forState:UIControlStateNormal];
                        break;
                    case PM:
                    case CM:
                    case PMS:
                    case CM_Above_Cost_Cap:
                    case CM_Not_Under_PMWS:
                    case New_Works_Above_70:
                    case New_Works_Below_70:
                        [btnMaintenanceType setTitle:[ApplicationDelegate getMaintenanceTypeName:typemaintenance] forState:UIControlStateNormal];
                        break;
                        
                    default:
                        break;
                }
            }
        }
        else if([delegate isKindOfClass:[DetailedItemViewController class]] && ((DetailedItemViewController *)delegate).itemType == Facility_Type){
            if ([[_dictSchedule objectForKey:@"categoryId"] intValue] == Maintenance)
            {
                typemaintenance = [[_dictSchedule objectForKey:@"maintenanceTypeId"] intValue];
                switch (typemaintenance) {
                    case 0:
                        [btnMaintenanceType setTitle:[dictLanguage objectForKey:@"maintenance-mgmt.add-new.select-maintenance-type"] forState:UIControlStateNormal];
                        break;
                    case PM:
                    case CM:
                    case PMS:
                    case CM_Above_Cost_Cap:
                    case CM_Not_Under_PMWS:
                    case New_Works_Above_70:
                    case New_Works_Below_70:
                        [btnMaintenanceType setTitle:[ApplicationDelegate getMaintenanceTypeName:typemaintenance] forState:UIControlStateNormal];
                        break;
                        
                    default:
                        break;
                }
            }
        }
        typeRequirement = [[_dictSchedule objectForKey:@"categoryTypeId"] intValue];
        switch (typeRequirement) {
            case 0:
                [btnTypeRequirment setTitle:[dictLanguage objectForKey:@"schedule.title-select"] forState:UIControlStateNormal];
                break;
            case MONTHLY:
                [btnTypeRequirment setTitle:[dictLanguage objectForKey:@"schedule.title-monthly"] forState:UIControlStateNormal];
                break;
            case QUATERLY:
                [btnTypeRequirment setTitle:[dictLanguage objectForKey:@"schedule.title-quaterly"] forState:UIControlStateNormal];
                break;
            case YEARLY:
                [btnTypeRequirment setTitle:[dictLanguage objectForKey:@"schedule.title-yearly"] forState:UIControlStateNormal];
                break;
            case TWO_YEARLY:
                [btnTypeRequirment setTitle:[dictLanguage objectForKey:@"schedule.title-two-yearly"] forState:UIControlStateNormal];
                break;
            case FIVE_YEARLY:
                [btnTypeRequirment setTitle:[dictLanguage objectForKey:@"schedule.title-five-yearly"] forState:UIControlStateNormal];
                break;
            case OTHER:
                [btnTypeRequirment setTitle:[dictLanguage objectForKey:@"schedule.title-other"] forState:UIControlStateNormal];
                break;
                
            default:
                break;
        }
        
    }
    else{
        if ([delegate isKindOfClass:[DetailedInfoViewController class]]){
            if ([[_dictSchedule objectForKey:@"categoryId"] intValue] == Maintenance)
            {
                [btnMaintenanceType setTitle:[dictLanguage objectForKey:@"liaison.title-select-type"] forState:UIControlStateNormal];
            }
        }
        else if([delegate isKindOfClass:[DetailedItemViewController class]] && ((DetailedItemViewController *)delegate).itemType == Facility_Type){
            [btnMaintenanceType setTitle:[dictLanguage objectForKey:@"maintenance-mgmt.add-new.select-maintenance-type"] forState:UIControlStateNormal];
        }
        [btnTypeRequirment setTitle:[dictLanguage objectForKey:@"schedule.title-select"] forState:UIControlStateNormal];
    }
    if(!isEditting)
    {
        if([delegate isKindOfClass:[DetailedItemViewController class]])
            ;
        else{
            [btnLastUpdate setTitle:@"" forState:UIControlStateNormal];
            [_dictSchedule setObject:@"" forKey:@"lastUpdate"];
        }
    }
    [self.tbScheduleInspection reloadData];
}

- (void)saveScheduleInfo{
    NSString *messageError = nil;
    BOOL isRequirementType = YES;
    if ([[_dictSchedule objectForKey:@"categoryId"] intValue] == Maintenance){
        if (isEditting && !isCheckEditting)
            ;
        else{
            if ([delegate isKindOfClass:[DetailedInfoViewController class]]){
                if (btnMaintenanceType && [[btnMaintenanceType titleForState:UIControlStateNormal] isEqualToString:[dictLanguage objectForKey:@"liaison.title-select-type"]]) {
                    messageError = [dictLanguage objectForKey:@"schedule.title-required-select-type-maintenance"];
                }
            }
            else if([delegate isKindOfClass:[DetailedItemViewController class]] && ((DetailedItemViewController *)delegate).itemType == Facility_Type){
                if (btnMaintenanceType && [[btnMaintenanceType titleForState:UIControlStateNormal] isEqualToString:[dictLanguage objectForKey:@"maintenance-mgmt.add-new.select-maintenance-type"]]) {
                    messageError = [dictLanguage objectForKey:@"schedule.title-required-select-type-maintenance"];
                }
            }
            
        }
        switch ([[_dictSchedule objectForKey:@"maintenanceTypeId"] intValue]) {
            case 0:
            case PM:
            case CM:
            case PMS:
                break;
                
            default:
            {
                isRequirementType = NO;
                
            }
                break;
        }
    }
    if (!messageError) {
        if (isRequirementType && [[btnTypeRequirment titleForState:UIControlStateNormal] isEqualToString:[dictLanguage objectForKey:@"schedule.title-select"]]) {
            messageError = [dictLanguage objectForKey:@"schedule.title-required-select-type-requirement"];
        }
    }
    if (!messageError) {
        if ([btnStartDate titleForState:UIControlStateNormal] == nil || [[btnStartDate titleForState:UIControlStateNormal] isEqualToString:@""]) {
            messageError = [dictLanguage objectForKey:@"schedule.maintenance-schedule-required-select-starting-date"];
        }
    }
    if (!messageError) {
        if (tvRemark.text == nil || [tvRemark.text isEqualToString:@""]) {
            messageError = [dictLanguage objectForKey:@"schedule.title-required-input-re-mark"];
        }
    }
    if (messageError) {
        [self showErrorMessage:messageError];
        return;
    }
    [_dictSchedule setObject:kScheduleDocType forKey:@"Table"];
    [_dictSchedule setObject:[NSNumber numberWithBool:NO] forKey:@"wasRead"];
    
    NSString *startDate = [NSDate stringFormatDateFullFromDate:[NSDate dateFormatTimeDateFromString:startDateStr]];
    
    NSTimeInterval numberDate = [ApplicationDelegate getNumberDateTypeRequirement:typeRequirement];
    
    NSString *lastDate = [NSDate stringFormatDateFullFromDate:[[NSDate dateFormatDateFullFromString:startDate] dateByAddingTimeInterval:numberDate * 24*60*60]];
    
    if (_dictSchedule && [[_dictSchedule objectForKey:@"categoryId"] intValue] == Maintenance){
        switch ([[_dictSchedule objectForKey:@"maintenanceTypeId"] intValue]) {
            case 0:
            case PM:
            case CM:
            case PMS:
                break;
                
            default:
            {
                lastDate = @"";
                
            }
                break;
        }
    }
    if (startDate)
        [_dictSchedule setObject:startDate forKey:@"startDate"];

    //khi update schedule thi ko update last update
//    if (lastDate)
//        [_dictSchedule setObject:lastDate forKey:@"lastUpdate"];

    
    if (tvRemark.text == nil || [tvRemark.text isEqualToString:@""])
        [_dictSchedule setObject:@"" forKey:@"reMark"];
    else
        [_dictSchedule setObject:tvRemark.text forKey:@"reMark"];
    
    NSString *messageFailed = nil;
    if (isEditting){
        NSError *error;
        [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:_dictSchedule error:&error];
        if (error)
            messageFailed = [dictLanguage objectForKey:@"schedule.schedule-failed-update"];
    }
    else{
        //if add new, last date = @""
        if ([delegate isKindOfClass:[DetailedItemViewController class]])
            ;
        else
            [_dictSchedule setObject:@"" forKey:@"lastUpdate"];
        [_dictSchedule setObject:[[NSUserDefaults standardUserDefaults] objectForKey:ACCOUNT_ID] forKey:@"userId"];
        [_dictSchedule setObject:[NSNumber numberWithInt:1] forKey:@"status"];
        NSError *error;
        [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:_dictSchedule error:&error];
        if (error)
            messageFailed = [dictLanguage objectForKey:@"schedule.schedule-failed-add"];
            
    }
    if (messageFailed) {
        [self showErrorMessage:messageFailed];
        return;
    }
    else{
        NSString *message;
        if (isEditting)
            message = [dictLanguage objectForKey:@"schedule.schedule-update-success"];
        else
            message = [dictLanguage objectForKey:@"schedule.schedule-add-success"];
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        
    }
    
    for (id controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[ListScheduleViewController class]]) {
            [((ListScheduleViewController *)controller) updateScheduleInfo:_dictSchedule isEdit:isEditting];
            break;
        }
    }
    
    if ([delegate isKindOfClass:[DetailedItemViewController class]])
    {
        [((DetailedItemViewController *)delegate) refreshListSchedule];
        [self.navigationController popToViewController:delegate animated:YES];
    }
    else
        [self.navigationController popToRootViewControllerAnimated:YES];
    
}
- (void)saveScheduleAfterUpdateMaintenance:(NSMutableDictionary*)_inputMaintenanceDict {
    //update maintenanceId for this schedule
    [_dictSchedule setObject:[_inputMaintenanceDict objectForKey:@"_id"] forKey:@"maintenanceId"];
    [_dictSchedule setObject:kScheduleDocType forKey:@"Table"];
    
    NSString *startDate = [NSDate stringFormatDateFullFromDate:[NSDate dateFormatTimeDateFromString:startDateStr]];
    
    NSString *endDate = [NSDate stringFormatDateFullFromDate:[NSDate dateFormatTimeDateFromString:endDateStr]];
    
    if (startDate) {
        [_dictSchedule setObject:startDate forKey:@"startDate"];
    }
    
    if (tvRemark.text == nil || [tvRemark.text isEqualToString:@""])
        [_dictSchedule setObject:@"" forKey:@"reMark"];
    else
        [_dictSchedule setObject:tvRemark.text forKey:@"reMark"];
    if([delegate isKindOfClass:[DetailedItemViewController class]])
        ;
    else
        [_dictSchedule setObject:[NSDate stringFormatDateFullFromDate:[NSDate date]] forKey:@"lastUpdate"];
    
    //update date updated
    [_dictSchedule setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"dateUpdated"];
    NSError *error;
    [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:_dictSchedule error:&error];
    
    //update schedulingId for its maintenance
    CBLDocument *maintenanceDoc = [CouchBaseLiteLib getDocumentById:[_inputMaintenanceDict objectForKey:@"_id"]];
    NSMutableDictionary *newMaintenanceDict = [maintenanceDoc.properties mutableCopy];
    [newMaintenanceDict setObject:[_dictSchedule objectForKey:@"_id"] forKey:@"scheduleId"];
    [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:newMaintenanceDict error:&error];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self addTopBar];
    if (self.navBar)
    {
        self.navBar.navBarViewDelegate = self;
        self.navBar.titleLabel.text = [dictLanguage objectForKey:@"schedule.title-schedule"];
    }
    
    lblTitleSchedule.text = [dictLanguage objectForKey:@"schedule.title-schedule"];
    
    lblInServiceType = [[UILabel alloc] initWithFrame:CGRectMake(430, 8, 420, 34)];
    lblInServiceType.numberOfLines = 0;
    lblInServiceType.textColor = [UIColor darkGrayColor];
    lblInServiceType.font = [UIFont systemFontOfSize:15];
    
    btnWorkingType = [[CustomButton alloc] initWithFrame:CGRectMake(410, 10, 440, 30)];
    btnItemType = [[CustomButton alloc] initWithFrame:CGRectMake(410, 10, 440, 30)];
    
    btnMaintenanceType = [[CustomButton alloc] initWithFrame:CGRectMake(410, 10, 440, 30)];
    
    btnTypeRequirment = [[CustomButton alloc] initWithFrame:CGRectMake(410, 10, 440, 30)];
    btnStartDate = [[CustomButton alloc] initWithFrame:CGRectMake(410, 10, 440, 30)];
    
    btnLastUpdate = [[CustomButton alloc] initWithFrame:CGRectMake(410, 10, 440, 30)];

    tvRemark = [[UITextView alloc] initWithFrame:CGRectMake(425, 10, 425, 86)];
    tvRemark.backgroundColor = [UIColor clearColor];
    tvRemark.font = [UIFont systemFontOfSize:15];
    tvRemark.autocorrectionType = UITextAutocorrectionTypeNo;
    tvRemark.textColor = [UIColor darkGrayColor];
    
    lblBorderRemark = [[UILabel alloc] initWithFrame:CGRectMake(410,10, 440, 90)];
    lblBorderRemark.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    lblBorderRemark.layer.borderWidth = 1;
    
    [btnMaintenanceType addTarget:self action:@selector(selectMaintenanceType:) forControlEvents:UIControlEventTouchUpInside];
    [btnTypeRequirment addTarget:self action:@selector(selectTypeRequirement:) forControlEvents:UIControlEventTouchUpInside];
    [btnStartDate addTarget:self action:@selector(selectStartDate:) forControlEvents:UIControlEventTouchUpInside];
    
    if ([_dictSchedule objectForKey:@"lastUpdate"] && ![[_dictSchedule objectForKey:@"lastUpdate"] isEqualToString:@""]) {
        [btnLastUpdate setTitle:[NSString stringWithFormat:@"%@",[NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[_dictSchedule objectForKey:@"lastUpdate"]]]] forState:UIControlStateNormal];
    }
    else
//        [btnLastUpdate setTitle:[NSString stringWithFormat:@"%@",[NSDate stringFormatTimeDateFromDate:[NSDate date]]] forState:UIControlStateNormal];
        [btnLastUpdate setTitle:@"" forState:UIControlStateNormal];
    
    if (_dictSchedule && [[_dictSchedule objectForKey:@"categoryId"] intValue] == Maintenance){
        switch ([[_dictSchedule objectForKey:@"maintenanceTypeId"] intValue]) {
            case 0:
            case PM:
            case CM:
            case PMS:
                break;
                
            default:
            {
                [_dictSchedule setObject:@"" forKey:@"lastUpdate"];
                [btnLastUpdate setTitle:@"" forState:UIControlStateNormal];
                
            }
                break;
        }
    }
    if ([_dictSchedule objectForKey:@"startDate"]) {
        [btnStartDate setTitle:[NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[_dictSchedule objectForKey:@"startDate"]]] forState:UIControlStateNormal];
        startDateStr = [NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[_dictSchedule objectForKey:@"startDate"]]];
    }
   
    if ([_dictSchedule objectForKey:@"reMark"] == nil || [[_dictSchedule objectForKey:@"reMark"] isEqualToString:@""])
        ;
    else
        tvRemark.text = [_dictSchedule objectForKey:@"reMark"];
    
    [self reloadInfoSchedule];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark FilterViewController
- (void)didSelectFilter:(NSMutableDictionary *)filterDict{
    [self didmissPopoverController];
    if ([[filterDict objectForKey:@"filterType"] intValue] == filter_maintenance) {
        [btnMaintenanceType setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
        
        [_dictSchedule setObject:[filterDict objectForKey:@"filterName"] forKey:@"maintenanceType"];
        [_dictSchedule setObject:[filterDict objectForKey:@"index"] forKey:@"maintenanceTypeId"];
        
        typeRequirement = [[filterDict objectForKey:@"index"] intValue];
        
        if([delegate isKindOfClass:[DetailedItemViewController class]])
            ;
        else{
            
            if ([_dictSchedule objectForKey:@"lastUpdate"] && ![[_dictSchedule objectForKey:@"lastUpdate"] isEqualToString:@""]) {
                [btnLastUpdate setTitle:[NSString stringWithFormat:@"%@",[NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:[_dictSchedule objectForKey:@"lastUpdate"]]]] forState:UIControlStateNormal];
            }
            else
                //            [btnLastUpdate setTitle:[NSString stringWithFormat:@"%@",[NSDate stringFormatTimeDateFromDate:[NSDate date]]] forState:UIControlStateNormal];
                [btnLastUpdate setTitle:@"" forState:UIControlStateNormal];
            
            if (_dictSchedule && [[_dictSchedule objectForKey:@"categoryId"] intValue] == Maintenance){
                switch ([[_dictSchedule objectForKey:@"maintenanceTypeId"] intValue]) {
                    case 0:
                    case PM:
                    case CM:
                    case PMS:
                        break;
                        
                    default:
                    {
                        [_dictSchedule setObject:@"" forKey:@"lastUpdate"];
                        [btnLastUpdate setTitle:@"" forState:UIControlStateNormal];
                        
                    }
                        break;
                }
            }
        }

        [self.tbScheduleInspection reloadData];
    }
    else{
        [btnTypeRequirment setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
        
        [_dictSchedule setObject:[filterDict objectForKey:@"filterName"] forKey:@"categoryType"];
        [_dictSchedule setObject:[filterDict objectForKey:@"index"] forKey:@"categoryTypeId"];
        
        typeRequirement = [[filterDict objectForKey:@"index"] intValue];
        
        NSString *lastUpdate    = [_dictSchedule objectForKey:@"lastUpdate"];
        
        if (lastUpdate != nil && ![lastUpdate isEqualToString:@""]) {
            NSTimeInterval numberDate = [ApplicationDelegate getNumberDateTypeRequirement:typeRequirement];
            
            NSString *startDate = [NSDate stringFormatDateFullFromDate:[[NSDate dateFormatDateFullFromString:lastUpdate] dateByAddingTimeInterval:numberDate * 24*60*60]];
            
            [_dictSchedule setObject:startDate forKey:@"startDate"];
            startDateStr = startDate;
            
            startDate = [NSDate stringFormatTimeDateFromDate:[NSDate dateFormatDateFullFromString:startDate]];
            [btnStartDate setTitle:startDate forState:UIControlStateNormal];
        }
    }

//    typemaintenance = [[filterDict objectForKey:@"index"] intValue];
}

#pragma mark ListPersonInChargeViewDelegate

- (void)didSelectPersonInCharge:(NSMutableDictionary *)person{
    [self didmissPopoverController];
}

#pragma mark - DatePickerView Delegate
- (BOOL)validFromDate:(NSString *)fromDate toDate:(NSString *)toDate{
    if (fromDate == nil || toDate == nil)
        return YES;
    NSDate *date1 = [NSDate dateFormatTimeDateFromString:fromDate];
    NSDate *date2 = [NSDate dateFormatTimeDateFromString:toDate];
    
    NSString *messageError = nil;
    if (date1 == nil) {
        messageError = [dictLanguage objectForKey:@"schedule.maintenance-schedule-invalid-select-start-date"];
    }
    else if (date2 == nil)
        messageError = [dictLanguage objectForKey:@"schedule.maintenance-schedule-invalid-select-end-date"];
    if ([date1 compare:date2] == NSOrderedDescending) {
        if (indexSelectDate == StartDateIndex) {
            messageError = [dictLanguage objectForKey:@"schedule.maintenance-schedule-invalid-select-start-date"];
        }
        else
            messageError = [dictLanguage objectForKey:@"schedule.maintenance-schedule-invalid-select-end-date"];
    }
    if (messageError == nil)
        return YES;
    else{
        [self showErrorMessage:messageError];
        return NO;
    }
}
- (void)didSelectDatePicker:(NSDate *)date{
    [self didmissPopoverController];
    
    if (![self validFromDate:[NSDate stringFormatTimeDateFromDate:date] toDate:endDateStr])
        return;
    
    startDateStr = [NSDate stringFormatTimeDateFromDate:date];
    [btnStartDate setTitle:startDateStr forState:UIControlStateNormal];
}
- (void)didCancelSectDatePicker{
    [self didmissPopoverController];
}

#pragma mark - NavViewDelegate

- (void)didClickedLeftButton {
    if (isCheckEditting) {
        //check from Maintenance detail, pop to previous view controller
        if ([delegate isKindOfClass:[MaintenanceDetailedViewController class]]) {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else {
            isCheckEditting = NO;
            [self reloadInfoSchedule];
            [self.tbScheduleInspection reloadData];
        }
    }
    else
    {
        
        if ([delegate isKindOfClass:[DetailedItemViewController class]])
        {
//            [((DetailedItemViewController *)delegate) handleMainAction:((DetailedItemViewController *)delegate).btnAIP];
            [self.navigationController popToViewController:delegate animated:YES];
        }
        else
            [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didClickedRightButton
{
    if (isEditting) {
        if (isCheckEditting) {
            if ([delegate isKindOfClass:[MaintenanceDetailedViewController class]]) {
                SelectContractorViewController *controller = [[SelectContractorViewController alloc] initWithNibName:@"SelectContractorViewController" bundle:nil parent:self];
                controller.inputMaintenanceDict = inputMaintenanceDict;
                controller.inputInspectionDict  = inputInspectionDict;
                UINavigationController *naviController = [[UINavigationController alloc] initWithRootViewController:controller];
                naviController.modalPresentationStyle = UIModalPresentationPageSheet;
                [self presentModalViewController:naviController animated:YES];
  
                if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
                    naviController.view.superview.frame = CGRectMake(312, 100, 400, 260);
            }
            else
                [self saveScheduleInfo];
            }
        else{
            //check permission
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSMutableDictionary *permissionDict;
            if ([delegate isKindOfClass:[DetailedItemViewController class]]) {
                int itemType = ((DetailedItemViewController*)delegate).itemType;
                if (itemType == Building_Type)
                    permissionDict = [[userDefaults objectForKey:BUILDING_PERMISSION] objectForKey:@"aip"];
                else
                    permissionDict = [[userDefaults objectForKey:FACILITY_PERMISSION] objectForKey:@"amp"];
            }
            else {
                permissionDict = [userDefaults objectForKey:SCHEDULE_PERMISSION];
            }
            BOOL isEdit = [[permissionDict objectForKey:@"update"] boolValue];
            if (!isEdit) {
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                return;
            }
            
            isCheckEditting = YES;
            [self.tbScheduleInspection reloadData];
            [self reloadInfoSchedule];
        }
    }
    else{
        [self saveScheduleInfo];
    }
}
#pragma mark - TextView delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"] && range.length == 0) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}
#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    int numberRow = 0;
    if ([delegate isKindOfClass:[DetailedItemViewController class]]) {
        if(((DetailedItemViewController *)delegate).itemType == Facility_Type)
            numberRow = 5;
        else
            numberRow = 4;
    }
    else
        numberRow = 7;
    if (_dictSchedule && [[_dictSchedule objectForKey:@"categoryId"] intValue] == Maintenance){
        switch ([[_dictSchedule objectForKey:@"maintenanceTypeId"] intValue]) {
            case 0:
            case PM:
            case CM:
            case PMS:
                break;
                
            default:
                numberRow -= 1;
                break;
        }
    }
    if (indexPath.row == numberRow - 1)
        return 100;
    return 50;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    int numberRow = 0;
    if ([delegate isKindOfClass:[DetailedItemViewController class]]) {
        if(((DetailedItemViewController *)delegate).itemType == Facility_Type)
            numberRow = 5;
        else
            numberRow = 4;
    }
    else
        numberRow = 7;
    if (_dictSchedule && [[_dictSchedule objectForKey:@"categoryId"] intValue] == Maintenance){
        switch ([[_dictSchedule objectForKey:@"maintenanceTypeId"] intValue]) {
            case 0:
            case PM:
            case CM:
            case PMS:
                break;
                
            default:
                numberRow -= 1;
                break;
        }
    }
    return numberRow;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(172, 14, 300, 22)];
    lblTitle.backgroundColor = [UIColor clearColor];
    lblTitle.textColor = [UIColor darkGrayColor];
    lblTitle.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
    int row = indexPath.row;
    if ([delegate isKindOfClass:[DetailedItemViewController class]])
    {
        if(((DetailedItemViewController *)delegate).itemType == Facility_Type)
            row = row + 2;
        else
            row = row + 3;
        
    }
    if ([[_dictSchedule objectForKey:@"categoryId"] intValue] == Maintenance){
        switch ([[_dictSchedule objectForKey:@"maintenanceTypeId"] intValue]) {
            case 0:
            case PM:
            case CM:
            case PMS:
                break;
                
            default:
                if (row >= 3)
                    row += 1;
                break;
        }
    }
    switch (row) {
        case 0:
        {
            lblTitle.text = [dictLanguage objectForKey:@"schedule.title-work-type"];
            
            [cell.contentView addSubview:btnWorkingType];
            
        }
            break;
        case 1:
        {
            lblTitle.text = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance.item-type"];
            
            [cell.contentView addSubview:btnItemType];
            
        }
            break;
        case 2:
        {
            if ([delegate isKindOfClass:[DetailedItemViewController class]]){
                lblTitle.text = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance.type"];
                
                [cell.contentView addSubview:btnMaintenanceType];
            }
            else{
                lblTitle.text = [dictLanguage objectForKey:@"schedule.title-in-service-item"];
                
                [cell.contentView addSubview:lblInServiceType];
            }
        }
            break;
        case 3:
        {
            lblTitle.text = [dictLanguage objectForKey:@"schedule.title-type-requirement"];

            [cell.contentView addSubview:btnTypeRequirment];
            
        }
            break;
        case 4:
        {
            lblTitle.text = [dictLanguage objectForKey:@"schedule.title-last-done"];
            
            [cell.contentView addSubview:btnLastUpdate];
        }
            break;
        case 5:
        {
            lblTitle.text = [dictLanguage objectForKey:@"schedule.title-next-done"];
            
            [cell.contentView addSubview:btnStartDate];
            
            if (!isEditting || isCheckEditting) {
                UIButton *btnEdit = [UIButton buttonWithType:UIButtonTypeCustom];
                btnEdit.frame = CGRectMake(855, 10, 29, 29);
                [btnEdit setImage:[UIImage imageNamed:@"iconDatePicker.png"] forState:UIControlStateNormal];
                [btnEdit addTarget:self action:@selector(selectStartDate:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:btnEdit];
            }

            
        }
        break;
        
        case 6:
        {
            lblTitle.text = [dictLanguage objectForKey:@"schedule.title-re-mark"];
            
            [cell.contentView addSubview:lblBorderRemark];
            
            [cell.contentView addSubview:tvRemark];
        }
            break;
            
        default:
            break;
    }
    [cell.contentView addSubview:lblTitle];
    // Configure the cell...
    
    return cell;
}
- (void) finishUpdateMaintenance {
    [self.navigationController popToRootViewControllerAnimated:YES];
}
@end
